package com.rdk.action;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.rdk.constant.Forward;
import com.rdk.constant.StrConstant;
import com.rdk.entity.TUser;
import com.rdk.service.TShareMessageService;
import com.rdk.service.TShareService;
import com.rdk.service.TUserGroupService;
import com.rdk.service.TUserService;
import com.rdk.utils.BusinessException;
import com.rdk.utils.CommonUtil;
import com.rdk.utils.DateUtil;
import com.rdk.utils.HmacSHA256Utils;
import com.rdk.utils.LogUtil;
import com.rdk.utils.PubFun;
import com.rdk.utils.StringUtil;
import com.rdk.utils.UploadService;
import com.rdk.wechat.util.SystemConfig;

/**
 * 分享app
 * @author wang_lei
 *
 */
@Controller
public class ShareAction extends BaseAction{
	@Autowired
    private TUserService userService;
	
	@Autowired
    private TShareService shareService;
	
	@Autowired
    private TUserGroupService userGroupService;
	
	@Autowired
	private TShareMessageService shareMessageService;
	
	/**
	 * 分享首页
	 * 
	 * @param request
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "feed")
	public String toShareIndex(HttpServletRequest request, ModelMap model){
		String userId = CommonUtil.getSession(request, StrConstant.PARAM_USERID);
		if("0".equals(userId)){
			userId = CommonUtil.getRequest(request, StrConstant.PARAM_USERID);
		}
		String timestamp = DateUtil.getCurrentDateTime();
        try {
        	String _timestamp = String.valueOf(System.currentTimeMillis()), _nonce = PubFun.getRandom(4), _digest = HmacSHA256Utils
                    .digest(SystemConfig.readValue("key"), userId, _timestamp, _nonce);
            model.put(StrConstant.PARAM_TIMESTAMP, _timestamp);
            model.put(StrConstant.PARAM_NONCE, _nonce);
            model.put(StrConstant.PARAM_DIGEST, _digest);
            TUser user = userService.findUserById(userId);
            JSONArray feeds = shareService.findFeeds(userId, timestamp, 0);
            if (user == null) {
                throw new Exception("用户信息不存在！");
            }
            JSONArray friends = (JSONArray)CommonUtil.getSessionObj(request, "friends");
            
            if(null == friends){
            	friends =  userService.findUserFriends(userId);
    			CommonUtil.setSession(request, "friends",friends);
    		}
    		
            model.put("user", user.getUserInfo());
            model.put("feeds", feeds);
            model.put(StrConstant.TIMESTAMP, timestamp);
            model.put(StrConstant.OFFSET, StrConstant.PAGE_SIZE);
            model.put("next", feeds.size() == StrConstant.PAGE_SIZE);
            //model.put("messageCount", shareMessageService.getUnreadMessageCount(userId));
            model.put("userGroup", userGroupService.findUserGroup(userId));
            model.put("friends",friends);
        } catch (Exception e) {
            LogUtil.getLogger().error(e);
            // e.printStackTrace();
            model.put("error", e.getMessage());
            return Forward.ActionPage.EXCEPTION;
        }
        
		return Forward.ActionPage.SHARE_INDEX;
	}
	
	/**
	 * 分享首页
	 * 
	 * @param request
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "write")
	public String toWriteIndex(HttpServletRequest request, ModelMap model){
		return Forward.ActionPage.WRITESHARE;
	}
	
	/**
	 * 获取分享详情
	 * 
	 * @param request
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "share/{shareId}")
	public String queryShareDetail(@PathVariable String shareId,HttpServletRequest request, ModelMap map){
		try {
			String userId = CommonUtil.getSession(request, StrConstant.PARAM_USERID);
			if("0".equals(userId)){
				userId = CommonUtil.getRequest(request, StrConstant.PARAM_USERID);
			}
            if (!"undefined".equals(shareId)) {
            	map.put("share", shareService.findFeed(shareId, userId));
            }
        } catch (Exception e) {
            LogUtil.getLogger().error(e);
            // e.printStackTrace();
            map.put("error", e.getMessage());
            return Forward.ActionPage.EXCEPTION;
        }
		return Forward.ActionPage.SHARE_DETAIL;
	}
	
	/**
	 * 点击用户名
	 * 
	 * @param request
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "u/{userId}")
	public String queryUserShare(@PathVariable String userId,HttpServletRequest request, ModelMap model){
		String timestamp = DateUtil.getCurrentDateTime();
        String loginId = CommonUtil.getSession(request, StrConstant.PARAM_USERID);
		if("0".equals(loginId)){
			loginId = CommonUtil.getRequest(request, StrConstant.PARAM_USERID);
		}
        JSONArray feeds = shareService.findUserShare(userId, loginId, timestamp, 0);
        model.put("feeds", feeds);
        model.put("userId", userId);
        model.put(StrConstant.OFFSET, StrConstant.PAGE_SIZE);
        model.put(StrConstant.TIMESTAMP, timestamp);
        model.put("next", feeds.size() == StrConstant.PAGE_SIZE);
		return Forward.ActionPage.SHARE_FRIEND;
	}
	
	/**
	 * 点击@的好友
	 * 
	 * @param request
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "n/{userName}")
	public String queryUserShareByName(@PathVariable String userName,HttpServletRequest request, ModelMap model){
		String timestamp = DateUtil.getCurrentDateTime();
		String loginId = CommonUtil.getSession(request, StrConstant.PARAM_USERID);
		if("0".equals(loginId)){
			loginId = CommonUtil.getRequest(request, StrConstant.PARAM_USERID);
		}
		/*String userNameTemp = "";
		System.out.println("-----------userName;" + userName);*/
		/*try {
			userNameTemp = new String(userName.getBytes("ISO8859-1"),"UTF-8");
			System.out.println("-----------new String;" + new String(userName.getBytes("ISO8859-1"),"UTF-8"));
			System.out.println("-----------userNameTemp;" + userNameTemp);
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			System.out.println(e1.getMessage());
			e1.printStackTrace();
		}
		userName = userNameTemp;*/
		System.out.println("-----------userName;" + userName);
		JSONArray feeds = null;
        try {
            feeds = shareService.findUserShareByName(userName, loginId, timestamp, 0);
        } catch (BusinessException e) {
            LogUtil.getLogger().error(e);
            // e.printStackTrace();
            model.put("error", e.getMessage());
            return Forward.ActionPage.EXCEPTION;
        }
        model.put("feeds", feeds);
        model.put(StrConstant.OFFSET, StrConstant.PAGE_SIZE);
        model.put(StrConstant.TIMESTAMP, timestamp);
        model.put("next", feeds.size() == StrConstant.PAGE_SIZE);
		return Forward.ActionPage.SHARE_FRIEND;
	}
	
	
	/**
     * 分享翻页
     * 
     * @param offset
     * @param 
     * @return
     */
	@RequestMapping(value = "feed/{offset}")
	public ModelAndView queryMoreShares(HttpServletRequest request, ModelMap map,@PathVariable int offset){
		
		//String userId = CommonUtil.getSession(request, StrConstant.USERID); 
		String timestamp = DateUtil.getCurrentDateTime();
		String userId = CommonUtil.getSession(request, StrConstant.PARAM_USERID);
		if("0".equals(userId)){
			userId = CommonUtil.getRequest(request, StrConstant.PARAM_USERID);
		}
		JSONArray feeds = shareService.findFeeds(userId, timestamp, offset);
		JSONObject json = new JSONObject();
		Map<String,Object> object = new HashMap<String,Object>();
		object.put("resultCode", 1);
		object.put("resultDes", "");
		json.put("feeds",feeds);
		//json.put("messageCount",offset == 0 ? shareMessageService.getUnreadMessageCount(userId): 0);
		json.put(StrConstant.TIMESTAMP, timestamp);
		json.put("next", feeds.size() == StrConstant.PAGE_SIZE);
		json.put("offset", offset + StrConstant.PAGE_SIZE);
		object.put("data", json);
		return new ModelAndView("jsonView", object);
	}
	
	/**
     * 写分享
     * 
     * @param offset
     * @param 
     * @return
     */
	@RequestMapping(value = "share")
	public ModelAndView addShare(HttpServletRequest request, ModelMap map){
		
		String userId = CommonUtil.getSession(request, StrConstant.PARAM_USERID);
		if("0".equals(userId)){
			userId = CommonUtil.getRequest(request, StrConstant.PARAM_USERID);
		}
		
		Map<String,Object> object = new HashMap<String,Object>();
		object.put("resultCode", "1");
		object.put("resultDes", "");
		try {
			shareService.addShare(request,userId);
		} catch (BusinessException e) {
			e.printStackTrace();
		}
		return new ModelAndView("jsonView", object);
	}
	
	/**
     * 删除分享
     * 
     * @param offset
     * @param 
     * @return
     */
	@RequestMapping(value = "share/{shareId}/forDel")
	public ModelAndView deleteShare(@PathVariable String shareId,HttpServletRequest request, ModelMap map)throws BusinessException{
		
		//String userId = CommonUtil.getSession(request, StrConstant.USERID); 
		
		Map<String,Object> object = new HashMap<String,Object>();
		object.put("resultCode", "1");
		object.put("resultDes", "");
		if (StringUtil.isEmpty(shareId)) {
            throw new BusinessException("获取分享失败");
        }
		String userId = CommonUtil.getSession(request, StrConstant.PARAM_USERID);
		if("0".equals(userId)){
			userId = CommonUtil.getRequest(request, StrConstant.PARAM_USERID);
		}
        shareService.deleteShare(shareId, userId);
		return new ModelAndView("jsonView", object);
	}
	
	/**
     * 转发
     * 
     * @param offset
     * @param 
     * @return
     */
	@RequestMapping(value = "{shareId}/forward")
	public ModelAndView forward(HttpServletRequest request, ModelMap map,@PathVariable String shareId) throws BusinessException{
		
		//String userId = CommonUtil.getSession(request, StrConstant.USERID); 
		String userId = CommonUtil.getSession(request, StrConstant.PARAM_USERID);
		if("0".equals(userId)){
			userId = CommonUtil.getRequest(request, StrConstant.PARAM_USERID);
		}
		Map<String,Object> object = new HashMap<String,Object>();
		shareService.forward(shareId, request,userId);
		object.put("resultCode", "1");
		object.put("resultDes", "");
		if (StringUtil.isEmpty(shareId)) {
            throw new BusinessException("获取分享失败");
        }
       
		return new ModelAndView("jsonView", object);
	}
	
	/**
     * 分页获取某个用户的分享
     * 
     * @param offset
     * @param 
     * @return
     */
	@RequestMapping(value = "u/{userId}/{offset}")
	public ModelAndView queryUserSharesMore(HttpServletRequest request, ModelMap map,@PathVariable String userId,@PathVariable int offset){
		
		//String userId = CommonUtil.getSession(request, StrConstant.USERID); 
		String loginId = CommonUtil.getSession(request, StrConstant.PARAM_USERID);
		if("0".equals(loginId)){
			loginId = CommonUtil.getRequest(request, StrConstant.PARAM_USERID);
		}
		Map<String,Object> object = new HashMap<String,Object>();
		object.put("resultCode", 1);
		object.put("resultDes", "");
		String timestamp = DateUtil.getCurrentDateTime();
        JSONObject json = new JSONObject();
        JSONArray feeds = shareService.findUserShare(userId, loginId, timestamp, offset);
        json.put("feeds", feeds);
        json.put("userId", userId);
        json.put(StrConstant.TIMESTAMP, timestamp);
        json.put("next", feeds.size() == StrConstant.PAGE_SIZE);
        json.put("offset", offset + StrConstant.PAGE_SIZE);
        object.put("data", json);
		return new ModelAndView("jsonView", object);
	}
	
	/**
     * 上传
     * 
     * @param offset
     * @param 
     * @return
     */
	@RequestMapping(value = "share/upload")
	public ModelAndView upload(MultipartFile file){
		
		//String userId = CommonUtil.getSession(request, StrConstant.USERID); 
		
		Map<String,Object> object = new HashMap<String,Object>();
		object.put("resultCode", 1);
		UploadService uploadService = new UploadService();
		String str = "";
		try {
			str = uploadService.saveFile(file);
		} catch (Exception e) {
			e.printStackTrace();
		}
		object.put("data", str);
		return new ModelAndView("jsonView",object);
	}
	
	/**
     * ajax上传
     * 
     * @param offset
     * @param 
     * @return
     */
	@RequestMapping(value = "share/ajaxFileUpload")
	public ModelAndView ajaxFileUpload(MultipartFile file){
		return upload(file);
	}
	
	/**
     * ajax上传
     * 
     * @param offset
     * @param 
     * @return
     */
	@RequestMapping(value = "share/uploadClient")
	public ModelAndView upload2(HttpServletRequest request, ModelMap map){
		
		//String userId = CommonUtil.getSession(request, StrConstant.USERID); 
		
		Map<String,Object> object = new HashMap<String,Object>();
		object.put("resultCode", 1);
		object.put("resultDes", "");
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> fileList = multipartRequest.getFiles("file");
        if (fileList.size() > 0) {
        	UploadService uploadService = new UploadService();
    		String str = "";
    		try {
    			str = uploadService.saveFile(fileList.get(0));
    			object.put("", str);
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
        } 
		return new ModelAndView("jsonView", object);
	}
}
